<template>
  <div class="app-container">
    <!-- 搜索表单保持不变 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域保持不变 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['web:product:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['web:product:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['web:product:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 商品卡片网格布局 -->
    <div class="product-grid-container">
      <div v-loading="loading" class="product-grid">
        <el-card
          v-for="item in productList"
          :key="item.id"
          class="product-card"
          shadow="hover"
        >
          <div class="card-header">
            <image-preview
              :src="item.coverImage"
              :width="200"
              :height="150"
              fit="cover"
            />
          </div>
          <div class="card-body">
            <div class="product-desc">{{ item.description || "暂无描述" }}</div>
            <div class="product-price">¥{{ item.price }}</div>
            <el-button type="primary" size="mini" @click.stop="showPaymentDialog"
              >购买</el-button
            >
          </div>
          <!-- 支付弹窗 -->
          <el-dialog
            :title="title"
            :visible.sync="showDialog"
            width="500px"
            append-to-body
          >
            <div class="dialog-content">
              <h1>请扫码支付 {{ item.price }} ¥</h1>
              <img
                src="@/assets/images/wechat_pay.jpg"
                alt="收款二维码"
                :width="300"
                :height="300"
              />
              <p>订单号: {{ orderId }}</p>
              <el-button @click="checkPayment">我已支付</el-button>
              <el-button @click="closeDialog">取消</el-button>
            </div>
          </el-dialog>
        </el-card>
      </div>
    </div>

    <!-- 成功支付 -->
    <el-dialog title="恭喜" :visible.sync="showPaySuccessDialog" width="30%">
      <span>您已成功完成支付，请等待人工客服确认订单</span>
    </el-dialog>

    <!-- 分页组件保持不变 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹窗表单保持不变 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <image-upload v-model="form.coverImage" />
        </el-form-item>
        <el-form-item label="详情描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProduct,
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
} from "@/api/web/product";
import { Dialog } from "element-ui";

export default {
  name: "Product",
  data() {
    return {
      //弹窗
      showDialog: false,
      //弹窗
      showPaySuccessDialog: false,
      //订单id
      orderId: "",
      // 当前产品
      currentProduct: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        price: null,
        coverImage: null,
        description: null,
        categoryId: null,
        status: null,
        userId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        price: [{ required: true, message: "价格不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      // 添加时间戳防止缓存
      const params = {
        ...this.queryParams,
        _t: Date.now(), // 时间戳参数，确保每次请求URL不同
      };

      listProduct(params)
        .then((response) => {
          console.log("API返回数据：", response.rows);
          this.productList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 点击图片，弹出支付
    showPaymentDialog() {
      this.showDialog = true;
      // this.currentProduct = item;
      生成订单号;
      this.orderId = "ORDER_" + Date.now();
      // 调用后端创建订单
      // this.$axios
      //   .post("/api/orders", {
      //     orderId: this.orderId,
      //     productId: item.id,
      //     amount: item.price,
      //     status: "unpaid",
      //   })
      //   .then(() => {
      //     this.showDialog = true;
      //     // 开始轮询检查支付状态
      //     this.checkInterval = setInterval(this.checkPayment, 5000);
      //   });
    },
    checkPayment() {
      this.showDialog = false;
      this.showPaySuccessDialog = true;
    },
    closeDialog() {
      this.showDialog = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productName: null,
        price: null,
        coverImage: null,
        description: null,
        categoryId: null,
        status: null,
        createTime: null,
        userId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getProduct(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商品编号为"' + ids + '"的数据项？')
        .then(function () {
          return delProduct(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.product-grid-container {
  padding: 20px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.product-card {
  transition: all 0.3s;
  margin-bottom: 20px;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
  }

  .card-body {
    padding: 15px;

    .product-name {
      font-size: 16px;
      margin: 0 0 10px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .product-price {
      color: #f56c6c;
      font-size: 18px;
      font-weight: bold;
      margin: 10px 0;
    }

    .product-desc {
      color: #666;
      font-size: 14px;
      height: 40px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }

  .card-footer {
    border-top: 1px solid #eee;
    padding: 10px 15px;
    text-align: right;
  }
}

/* 响应式适配 */
@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
}

@media (max-width: 480px) {
  .product-grid {
    grid-template-columns: 1fr;
  }
}
</style>
